package com.workfeng.message.controller;

import com.sun.corba.se.spi.ior.ObjectKey;
import com.workfeng.message.config.quartz.ScheduledJob;
import com.workfeng.message.config.quartz.SchedulerManager;
import com.workfeng.message.config.rabbitmq.MessageVo;
import com.workfeng.message.config.rabbitmq.Sender;
import com.workfeng.message.config.util.DateUtil;
import com.workfeng.message.utils.SuccessTip;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.Date;

@Controller
public class IndexController {

    @Autowired
    private Sender sender;
    @Autowired
    public SchedulerManager myScheduler;

    @RequestMapping("/index")
    public String index(Model model){

        // 假设用户1登陆
        model.addAttribute("userId","1");

        return "index";
    }

    @RequestMapping("/hello")
    @ResponseBody
    public Object hello(){

        // 发送给用户1的消息
        Integer[] ids = {1};
        String[] status = {"log","success","warn","error"};

        for(int i = 0; i< status.length;i++){
            MessageVo vo = new MessageVo();
            vo.setBussinessKey("00000"+i); // 消息唯一标识，将事件id作为消息唯一标识
            vo.setMessage("这是发送给用户 "+ids[0]+" 的 "+status[i]+" 状态的消息"); // 消息内容
            vo.setUserIds(Arrays.asList(ids)); //收消息的人
            vo.setStatus(status[i]); //警告
            vo.setType("toDo"); // 待办事项
            sender.send(vo);

            //定时任务
            try {
                myScheduler.startJob("0 0/1 * * * ?", vo.getBussinessKey(),"messages", ScheduledJob.class,vo);//每五分钟执行一次
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }

        return new SuccessTip();
    }

    @RequestMapping("/deletejob")
    @ResponseBody
    public Object deleteJob(){
        //删除定时任务
        try {
            myScheduler.deleteJob("000001","messages");
            System.out.println("定时消息任务key: "+ "000001" + " 已删除");
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return new SuccessTip();
    }
}
